if(!QS) {
    var QS = {};
}

QS.Pull = function(dataHandler,callback){
	this.callback=callback||{};
    this.dataHandler=dataHandler;
    /*this.rate={
        fast:5,
        slow:10,
        slower:15,
        slowest:30
    };*/
    this.intervalObj=null;
    this.batchQuerySize =50;
    this.timerObj=[];
	//this.OPERATION_OK=0;
    //this.rateKey=null;
	this.pullService=null;
	this.frequency=null;
    
	this.getDataHandler=function(){
		return this.dataHandler;
	};
	
	this.setPullService=function(pullService){
		this.pullService=pullService;
	};
	
    this.initConnection=function(pullService,frequency){
		this.pullService=pullService;
		this.frequency=frequency;
        //this.rateKey=rateKey;
        this._createIntervalObj();
		if(typeof this.callback.onSuccess=='function'){
			this.callback.onSuccess({
				errorCode:'0',
				errorMessage:'Connect pull server successfully.'
			});
		}
    };
    this.disconnect=function(){
		this._clearTimer();
		if(this.intervalObj!=null){
            clearInterval(this.intervalObj);
			this.intervalObj=null;
        }
	};
	
    this._createIntervalObj=function(){
        if(this.intervalObj!=null){
            clearInterval(this.intervalObj);
        }
        var self=this;
        this.intervalObj=setInterval(function(){
            var count =0,arr=[],flag = false;
            self._clearTimer();
            for(var gKey in gData){
                flag =false;
                if(typeof gData[gKey].subcribeNum!='undefined'&&gData[gKey].subcribeNum>0){
                    count ++;
                    if(gData[gKey].pullTicker && gData[gKey].pullTicker!=''){
                        arr.push(gData[gKey].pullTicker);
						/*var gk=gKey.split(":");
						if(typeof(mockExchangeCode)!="undefined"&&gk[0].indexOf(mockExchangeCode+"_")>-1) continue;
                        gData[gKey].pullTicker=gk[0]+":"+gData[gKey].type+":"+gk[1];*/
                    }
                    
                }
                if(count==self.batchQuerySize){      
                    with({temp:arr}){
                       self.timerObj.push(setTimeout(function(){
                           self._query(temp.join(",")); 
                       },100*self.timerObj.length));
                    }   
                    flag =true;
                    count=0;
                    arr=[];             
                }
            }
            if(!flag){
                self._query(arr.join(","));
            }
        },this.frequency);  
    };
    this.query=function(tickers,callback){
		var count=0;
		if(tickers.length>this.batchQuerySize){
			var subTickers=[];
			var c=Math.ceil(tickers.length/this.batchQuerySize);
			var cbNum=0;
			var returnItems = [];
			for(var i=0;i<c;i++){
				subTickers.push(tickers.slice(this.batchQuerySize*i,this.batchQuerySize*(i+1)));
				this._query(subTickers,function(o){
					cbNum++;
					returnItems = returnItems.concat(o.items||[]);
					if(cbNum>=c){
						callback({items:returnItems});
					}
				});
			}
		}else{
			this._query(tickers,callback);
		}
	};
    this._query=function(tickers,callback){
        if (tickers == "") {
            return false;
        }
        var self = this;
        $.getJSON(this.pullService + "?query="+tickers+"&cb=?",
			function(o) {
				if (typeof(o)=="undefined"||o.errorcode) {
					return false;
				}
				if(typeof callback=='function'){
					callback(o);
				}else{
					self.dataHandler.updateMarketPrice(o,gData);
				}
			}
		)
    };
    this._clearTimer=function(){
       for(var i=0,l=this.timerObj.length;i<l;i++){
           this.timerObj[i]=null;
           clearTimeout(this.timerObj[i]);
       }
       this.timerObj=[];    
    };
    
    this.batchSubscribe = function(channels){//['126.1.IBM','126.1.MSFT']
        var tickers;
		var count = 0;
        for(var i =0,l=channels.length;i<l;i +=this.batchQuerySize){
			var self = this;
			count++;
			tickers=channels.slice(i,i+this.batchQuerySize).join("}");
			with({tickers:tickers, count:count}){
				setTimeout(function(){
					self._query(tickers);
					//console.log(count + " " + tickers + " " + new Date())
				}, 1000*count);
			}
        }
    };
    
    this.batchUnsubscribe = function(channels){
        
    };
};